package rullekake.beans;

import java.util.LinkedList;
import java.util.List;
import rullekake.entities.Faculty;
import rullekake.beans.util.JsfUtil;
import rullekake.facade.FacultyFacade;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import rullekake.entities.Institution;
import rullekake.entities.Person;

/**
 * Klasse som håndterer oppretting/visning/endring av fakultetene
 *
 */

@ManagedBean (name="facultyController")
@SessionScoped
public class FacultyController {

    private Faculty current;
    private DataModel items = null;
    @EJB private rullekake.facade.FacultyFacade ejbFacade;
    @EJB private rullekake.facade.UsersFacade ejbUsersFacade;

    public FacultyController() {
    }

    public Faculty getSelected() {
        if (current == null) {
            current = new Faculty();
        }
        return current;
    }

    private FacultyFacade getFacade() {
        return ejbFacade;
    }


    public String prepareList() {
        recreateModel();
        return "faculty/List";
    }

    public String prepareView() {
        current = (Faculty)getItems().getRowData();
        return "faculty/View";
    }

    public String prepareCreate() {
        current = new Faculty();
        return "faculty/Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage("FacultyCreated");
            return "faculty/View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage("PersistenceErrorOccured");
            return null;
        }
    }

    public String prepareEdit() {
        current = (Faculty)getItems().getRowData();
        return "faculty/Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage("FacultyUpdated");
            return "faculty/View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage("PersistenceErrorOccured");
            return null;
        }
    }

    public String destroy() {
        try {
            getFacade().remove(current);
            recreateModel();
            return "faculty/List";
        } catch (Exception e) {
            JsfUtil.addErrorMessage("PersistenceErrorOccured");
            return null;
        }
    }

    public void setFacultiesByInstitution(Institution institution) {
        items = new ListDataModel(getFacade().findFacultiesByInstitution(institution));
    }

    public DataModel getItems() {
        if (items == null) {
            items = new ListDataModel(getFacade().findAll());
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectManyOfMyFaculties() {
        List<Faculty> faculties = new LinkedList<Faculty>();
        String loggedInAs = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
        Person thisPerson = ejbUsersFacade.findByUsername(loggedInAs).getPerson();


        // Går igjennom fagene og sjekker om de tilhørere brukerens institutt.
        for (Institution inst: thisPerson.getInstitutionCollection()){
                faculties.addAll(inst.getFacultyCollection());
        }
        return JsfUtil.getSelectItems(faculties, false);
    }


    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }
    
    @FacesConverter(forClass=Faculty.class)
    public static class FacultyControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            FacultyController controller = (FacultyController)facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "facultyController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Faculty) {
                Faculty o = (Faculty) object;
                return getStringKey(o.getFacultyId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: "+FacultyController.class.getName());
            }
        }
    }
}
